package com.wireless.service;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Queue;
import java.util.concurrent.LinkedBlockingDeque;

/**
 * The Class of chargeDevice
 * it can send data to chargeDevice,or get inputStream of chargeDevice
 * @author fang.junpeng
 *
 */
public class ChargeDevice {
	private String id;
	private boolean isActive = false;
	private Socket mSocket;
	private Queue<String> sendingMsg=null;
	private ChargeDeviceWritingThread wirtingThread = null;
	
	public ChargeDevice(String id,Socket socket) {
		this.id = id;
		mSocket = socket;
		sendingMsg = new LinkedBlockingDeque<String>();//
		OutputStream out = getOutputStream();
		if(null != out){
			wirtingThread = new ChargeDeviceWritingThread(out, sendingMsg);
			wirtingThread.start();
		}
	}
	
	public void send(String cmd) {
		synchronized (sendingMsg) {
			sendingMsg.add(cmd);
			//wirtingThread.notify();//wake up the writing Thread
			if(!wirtingThread.isAlive())
				wirtingThread.resume();
		}
	}
	
	public InputStream getInputStream() {
		InputStream in=null;
		try {
			in = mSocket.getInputStream();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return in;
	}
	
	private OutputStream getOutputStream() {
		OutputStream out=null;
		try {
			out = mSocket.getOutputStream();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return out;
	}
	
	public String getDeviceID(){
		return id;
	}
	
	public boolean isActive() {
		return isActive;
	}

	public void setActive(boolean isActive) {
		this.isActive = isActive;
	}
}

/**
 * If sendingMsg has data,ChargeDeviceWritingThread will send data out
 * else ChargeDeviceWritingThread will go sleeping
 * @author fang.junpeng
 *
 */
class ChargeDeviceWritingThread extends Thread{
	private OutputStream out=null;
	private Queue<String> sendingMsg=null;
	private volatile boolean bStop = false;
	
	public ChargeDeviceWritingThread(OutputStream out,Queue<String> sendingMsg) {
		this.out = out;
		this.sendingMsg = sendingMsg;
	}
	
	@SuppressWarnings("deprecation")
	@Override
	public void run() {
		while(!bStop){
			if(sendingMsg.isEmpty()){
				try {
					this.suspend();;//sleep
					//this.wait();
				} catch (Exception e) {
					e.printStackTrace();
					bStop = true;
				}
			}
			else {
				synchronized (sendingMsg) {
					try {
						if(!sendingMsg.isEmpty())
							out.write(sendingMsg.remove().getBytes());
					} catch (IOException e) {
						e.printStackTrace();
						bStop = true;
					}
				}
			}
		}
	}
	
}
